package org.btik.light.mobile.ui.factory;

import org.btik.light.mobile.meta.mo.DefaultDevMo;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class DevPanelFactory {
    private static final HashMap<String, Class<? extends DevPanel<?>>> devPanelMeta = new HashMap<>();

    private static final HashMap<String, Class<? extends DevPanelActivity>> devPanelActMeta = new HashMap<>();

    private static final HashMap<String, String> serialControllerPanelMeta = new HashMap<>();

    /**
     * @param dev 通过实例获取类，因而被注册的构造函数必须与 创建实例一致{@link org.btik.light.mobile.mo.DevMoFactory#newDev(String, Map)}
     *            其有可能返回子类。
     * @throws NullPointerException 请 调用此方法{@link #regDevPanelMeta(String, Class)} 注册类
     */
    public static DevPanel<?> newDevPanel(DefaultDevMo dev) {
        String devType = dev.getDevType();
        Class<? extends DevPanel<?>> devPanelClass = devPanelMeta.get(devType);
        if(devPanelClass == null){
            return null;
        }
        DevPanel<?> devPanel = null;
        try {
            Constructor<? extends DevPanel<?>> constructor = devPanelClass.getConstructor(dev.getClass());
            devPanel = constructor.newInstance(dev);
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException |
                 NoSuchMethodException e) {
            e.printStackTrace();
        }
        return devPanel;
    }

    public static void regDevPanelMeta(String devType, Class<? extends DevPanel<?>> clazz) {
        devPanelMeta.put(devType, clazz);
    }

    public static void regSerialControllerPanel(String serialControllerType, String clazz) {
        serialControllerPanelMeta.put(serialControllerType, clazz);
    }

    public static String getSerialControllerPanelNameByType(String serialControllerType) {
        return serialControllerPanelMeta.get(serialControllerType);
    }


    public static Class<? extends DevPanelActivity> getDevPanelType(String type) {
        return devPanelActMeta.get(type);
    }

    public static void regDevPanelActMeta(String devType, Class<? extends DevPanelActivity> clazz) {
        // activity的 name直接使用类名，不再额外映射
        devPanelActMeta.put(devType, clazz);
    }
}
